<template>
    <div class="system_role">
        <div class="content_panel_top">
            <h3 class="panel_title">
                <span>{{ $t('system.roleManage') }}</span>
            </h3>
            <el-form ref="form" :model="form" :rules="rules" :inline="false" class="module_form">
                <el-row :gutter="20">
                    <el-col :span="4">
                        <el-form-item prop="id">
                            <el-input v-model="form.name" maxlength="100" :placeholder="$t('system.roleName')" class="inputPhone"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="status">
                            <el-select v-model="form.status" clearable :placeholder="$t('common.status')" style="width: 100%"><!--状态-->
                                <el-option key="0" :label="$t('collection.closed')" :value="0"></el-option>
                                <el-option key="1" :label="$t('collection.activated')" :value="1"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item>
                            <el-button type="primary" @click="onSearch" icon="search">{{ $t('common.search') }}</el-button>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" align="right">
                        <el-button @click="editRole('add')" type="primary">{{ $t('system.addRole') }}</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <div class="data_list">
            <el-table :data="tableData" style="width: 100%;" :max-height="tableMaxHeight" >
                <el-table-column align="left" label="ID" prop="id" min-width="100"></el-table-column>
                <el-table-column align="left" :label="$t('system.roleName')" prop="name" min-width="140"><!--角色名--></el-table-column>
                <el-table-column :label="$t('common.createTime')" prop="createTime" min-width="170"><!--创建时间-->
                    <template slot-scope="{ row }">{{ row.createTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</template>
                </el-table-column>
                <el-table-column :label="$t('common.updateTime')" prop="updateTime" min-width="170"><!--更新时间-->
                    <template slot-scope="{ row }">{{ row.updateTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</template>
                </el-table-column>
                <el-table-column prop="status" :label="$t('common.status')" min-width="100"><!--状态-->
                    <template slot-scope="scope">
                        <el-switch @change="changeStatus(scope.row)" v-model="scope.row.status"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column align="left" :label="$t('system.resourceAuth')" min-width="120"><!--资源授权-->
                    <template slot-scope="scope">
                        <el-button @click="editRole('edit',scope.row)" :disabled="scope.row.status === false" type="text" size="small">{{ $t('system.bindingResource') }}</el-button><!--绑定资源-->
                    </template>
                </el-table-column>
            </el-table><!--end table-->
        </div>
        <div class="data_page">
            <pagination @pageChange="pageChange" :page="page"><!--分页组件--></pagination>
        </div>

        <!--绑定资源start-->
        <el-dialog :title="$t('system.roleInfo')" :visible.sync="editDialog.isVisible" width="500px">
            <el-form class="role_form" ref="roleForm" :model="roleForm" :rules="roleRules" label-position="top">
                <el-form-item :label="$t('system.roleName')" prop="roleName"><!--角色名称-->
                    <el-input v-model="roleForm.roleName" type="text" :disabled="editDialog.type === 'edit'" maxlength="100"></el-input>
                </el-form-item>
                <el-form-item :label="$t('system.resourceList')"><!--资源列表-->
                    <el-tree
                            ref="tree"
                            :data="resourceList"
                            show-checkbox
                            node-key="id"
                            :default-checked-keys="roleForm.checkedRes"
                            :props="defaultProps">
                    </el-tree>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="editRoleSubmit" type="primary">{{ $t('system.binding') }}</el-button><!--绑定-->
                <el-button @click="editDialog.isVisible = false" type="default">{{ $t('common.cancel') }}</el-button>
            </div>
        </el-dialog>
        <!--绑定资源end-->
    </div>
</template>

<script>
    import Pagination from '@/components/pagination';
    import mixin from '@/service/mixin';

    export default {
        name: 'systemAccount',
        components: {
            Pagination,
        },
        mixins: [mixin],
        data() {
            return {
                form: {
                    name: '',
                    status: '',
                },
                rules: {},
                bindResourceDialogShow: false,
                roleForm: {
                    roleId: '',
                    roleName: '',
                    checkedRes: []
                },
                roleRules: {
                    roleName: [
                        {required: true, message: this.$t('verify.plsInput'), trigger: 'blur'},
                        {pattern: /^[A-Za-z0-9]+$/, message: this.$t('verify.plsInputNumberAlp'), trigger: 'blur'}
                    ]
                },
                resourceList: [],
                editDialog: {
                    type: '',
                    isVisible: false,
                }
            };
        },
        computed: {
            defaultProps() {
                return {
                    children: 'children',
                    label: this.$i18n.locale === 'zhCN' ? 'cnName' : 'name',
                };
            },
        },
        methods: {
            getTableData(page = this.page) {
                const form = this.form;
                const params = {
                    name: form.name,
                    status: form.status,
                    pageNum: page.currentPage,
                    pageSize: this.page.pageSize
                };
                this.$api.systemManage.getRoleList(params).then((res) => {
                    const {status, data, error} = res;
                    if ('1' === status && error === '00000000') {
                        this.tableData = data.roleList || [];
                        this.tableData.forEach((item) => {
                            item.status = +item.status === 1;
                        });
                        this.page.recordsTotal = data.total;
                        this.page.currentPage = page.currentPage;
                        this.tableMaxHeight = window.document.body.clientHeight - 200;
                    }
                });
            },
            getResourceList() {
                this.roleForm.checkedRes = [];
                this.$api.systemManage.getResourceTree().then((res) => {
                    const {status, data, error} = res;
                    if ('1' === status && error === '00000000') {
                        if (data) {
                            this.resourceList = data;
                        }
                    }
                });
            },
            onSearch() {
                this.page.currentPage = 1;
                this.getTableData();
            },
            // 状态开关
            changeStatus(row) {
                this.$confirm(row.status === true  ? this.$tc('system.isOpenRole') : this.$tc('system.isCloseRole'), '', {
                    confirmButtonText: this.$tc('common.confirm'),
                    cancelButtonText: this.$tc('common.cancel'),
                    type: 'warning'
                }).then(() => {
                    this.operStatus(row);
                }).catch(() => {
                    row.status = !row.status;
                });
            },
            // 状态操作
            operStatus(row) {
                const params = {
                    id: row.id
                };
                this.$api.systemManage.deleteRole(params).then((res) => {
                    const { status, error, msg } = res;
                    if ('1' === status && '00000000' === error) {
                        this.$message({
                            message: this.$tc('common.successfulOperation'),
                            type: 'success',
                            showClose: true,
                            duration: 1000,
                        });
                    }
                    else if('70000120' === error) {
                        this.$message({
                            message: this.$tc('system.roleHasUsed'),
                            type: 'error',
                            showClose: true,
                            duration: 1000,
                        });
                    }
                    else {
                        this.$message({
                            message: msg || this.$tc('common.failedOperation'),
                            type: 'error',
                            showClose: true,
                            duration: 1000,
                        });
                    }
                    this.getTableData();
                });
            },
            editRole(type,row) {
                this.editDialog.type = type;
                if(type === 'add') {
                    this.editDialog.isVisible = true;
                    this.roleForm.roleName = '';
                    this.roleForm.checkedRes = [];
                    this.$nextTick(() => {
                        this.$refs.tree.setCheckedKeys(this.roleForm.checkedRes);
                        this.$refs.roleForm.clearValidate();
                    });
                }
                if(type === 'edit') {
                    // 根据Id查询对应的资源
                    const params = {
                        roleId: row.id
                    };
                    this.roleForm.roleName = row.name;
                    this.roleForm.roleId = row.id;
                    this.$api.systemManage.getResourceIdListByRoleId(params).then((res) => {
                        const {status, data, error} = res;
                        if ('1' === status && error === '00000000') {
                            this.editDialog.isVisible = true;
                            this.$nextTick(() => {
                                this.$refs.roleForm.clearValidate();
                            });
                            if (data instanceof Array) {
                                this.roleForm.checkedRes = Object.assign([], data);
                                this.$nextTick(() => {
                                    // 设置选中项
                                    this.$refs.tree.setCheckedKeys(this.roleForm.checkedRes);
                                });
                            }
                        }
                    });
                }
            },
            editRoleSubmit() {
                const type = this.editDialog.type;
                const form = this.roleForm;
                if(type === 'add') {// 新增
                    this.$refs.roleForm.validate((value) => {
                        if (value) {
                            if(this.$refs.tree.getCheckedKeys().length === 0) {
                                this.$message.error(this.$tc('system.plsChooseResource'));
                                return;
                            }
                            const params = {
                                name: form.roleName,
                                resourceIdList: this.$refs.tree.getCheckedKeys()
                            };
                            this.$api.systemManage.addRoleAndResource(params).then((res) => {
                                const {status, error, msg} = res;
                                if ('1' === status && error === '00000000') {
                                    this.editDialog.isVisible = false;
                                    this.$message({
                                        message: this.$tc('common.successfulOperation'),
                                        type: 'success',
                                        showClose: true,
                                        duration: 1000,
                                    });
                                    this.getTableData();
                                }
                                else if('70000124' === error) {
                                    this.$message({
                                        message: this.$tc('system.roleIsExist'),
                                        type: 'error',
                                        showClose: true,
                                        duration: 1000,
                                    });
                                }
                                else {
                                    this.$message({
                                        message: msg || this.$tc('common.failedOperation'),
                                        type: 'error',
                                        showClose: true,
                                        duration: 1000,
                                    });
                                }
                            });
                        }
                    });
                }
                if(type === 'edit') {// 编辑
                    if(this.$refs.tree.getCheckedKeys().length === 0) {
                        this.$message.error(this.$tc('system.plsChooseResource'));
                        return;
                    }
                    const params = {
                        roleId: form.roleId,
                        resourceIdList: this.$refs.tree.getCheckedKeys()
                    };
                    this.$api.systemManage.editRoleResource(params).then((res) => {
                        const {status, error, msg} = res;
                        if ('1' === status && error === '00000000') {
                            this.editDialog.isVisible = false;
                            this.$message({
                                message: this.$tc('common.successfulOperation'),
                                type: 'success',
                                showClose: true,
                                duration: 1000,
                            });
                        }
                        else {
                            this.$message({
                                message: msg || this.$tc('common.failedOperation'),
                                type: 'error',
                                showClose: true,
                                duration: 1000,
                            });
                        }
                    });
                }
            }
        },
        created() {
            // const user = this.$storage.get('user');
            this.getTableData();
            this.getResourceList();
        }
    };
</script>

<style lang="scss" scoped>
    .inputPhone {
        width: 100%;
    }

    .search {
        background-color: #fff;
        padding: 22px 40px 0;
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
    }

    .data_list {
        background-color: #fff;
        margin: 16px 24px;
        padding: 10px 16px;
    }

    .btn {
        margin-right: 15px;
    }

    .btn_red {
        /*border-color: #d9415c;*/
        color: #d9415c;
    }

    .role_form {
        /*padding: 0 16px;*/
    }

    .account_form_type {
        width: 100%;
    }
</style>
